//
//  UserExperienceVC.m
//  CoolTennisBall
//
//  Created by Coollang on 16/8/26.
//  Copyright © 2016年 CoolLang. All rights reserved.
//

#import "UserExperienceVC.h"
#import "UserCareerExpModel.h"
#import "UserGroup.h"
#import "UserItem.h"
#import "UserExperienceCell.h"
#import "UserAddExpController.h"
#import "NSString+Extension.h"
#import "UIView+Frame.h"
#import "MTButton.h"



@interface UserExperienceVC ()

@property (nonatomic, assign)BOOL isDeleting; // 正在删除
@property (nonatomic, weak) MTButton *bottomDeleteBtn;

/** 选中的条数 */
@property (nonatomic, strong) NSMutableArray *seleteExpArray;

@end

@implementation UserExperienceVC {
    BOOL _isChinese;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isChinese = [NSBundle currentLanguageIsChinese];
    NSString *editStr = NSLocalizedString(@"Edit", @"编辑");
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:editStr style:UIBarButtonItemStylePlain target:self action:@selector(deleteHandel:)];

    [self addRefreshheader];
    [self.tableView.mj_header beginRefreshing];
    
    [self creatAddExperienceView];
}
- (void)addRefreshheader {
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendHeaderWithShowTime:NO RefreshingBlock:^{
         [weakSelf loadData];
    }];
    
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (self.bottomDeleteBtn) {
        [self.bottomDeleteBtn removeFromSuperview];
        self.bottomDeleteBtn = nil;
    }
}
#pragma mark 加载数据和刷新界面
- (void)loadData {
    
    [self.groups removeAllObjects];
    self.groups = nil;
    
    UserGroup *group0 = [[UserGroup alloc] init];
    
    group0.headHeight = kAutoHei(30);
    [self.groups addObject:group0];
    
    [UserCareerExpModel requestCarceerExpListDatacompletion:^(NSArray *exps) {
        
        [self.tableView.mj_header endRefreshing];
        
        NSArray *sortExps = [exps sortedArrayUsingComparator:^NSComparisonResult(UserCareerExpModel *_Nonnull obj1,UserCareerExpModel * _Nonnull obj2) {
            
            return [obj1.Year compare:obj2.Year];
        }];
        
        [sortExps enumerateObjectsUsingBlock:^(UserCareerExpModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            UserItem *item = [UserItem itemWithTitle:obj.Year andSubTitle:obj.Career];
            item.ID = obj.ID;
            
            [group0.items addObject:item];
        }];
        
        [self.tableView reloadData];
    }];
}
- (void)reloadTableView {
    
    UserGroup *group = self.groups.firstObject;
    
    NSArray *sortExps = [group.items sortedArrayUsingComparator:^NSComparisonResult(UserItem *_Nonnull obj1,UserItem * _Nonnull obj2) {
        return [obj1.title compare:obj2.title];
    }];
    
    [group.items removeAllObjects];
    
    [group.items addObjectsFromArray:sortExps];
    
    [self.tableView reloadData];
}

#pragma mark - 用户事件操作
- (void)deleteHandel:(UIBarButtonItem *)item {
    
    self.isDeleting = !self.isDeleting;
    
    item.title = self.isDeleting == YES ? NSLocalizedString(@"Cancel", nil) :NSLocalizedString(@"Edit", @"删除");
    [self reloadTableView];
    
    if (self.isDeleting) {
        // 清空选中的数组
        [self.seleteExpArray removeAllObjects];
        self.seleteExpArray = nil;
    }
    
    [self CreatTrashBasketShow:self.isDeleting];
}


#pragma mark - UITableViewDelegate & UITableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  
    UserExperienceCell *cell = [UserExperienceCell settingViewCellTableView:tableView];
    
    UserGroup *group = self.groups[indexPath.section];
    UserItem *item = group.items[indexPath.row];
    
    [cell configerCellWithItem:item andState:self.isDeleting];
    
    [cell showLine:YES];
    
    cell.isSelectCell = NO;
    
    if (indexPath.row == 0) {
        [cell showSectionSepTopLineView:YES];
    }else {
        [cell showSectionSepTopLineView:NO];
    }

    return cell;
}

// 选中的哪一行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 取出对应的模型数据
    UserGroup *group = self.groups[indexPath.section];
    UserItem *item = group.items[indexPath.row];
    
    // 2.判断有没有block,有的话就执行
    if (item.block) {
        item.block();
        return;
    }
    
    if (!self.isDeleting) {
        UserAddExpController *addExpVc = [[UserAddExpController alloc] init];
        addExpVc.userItem = item;
        
        __weak typeof(item) weakItem = item ;
        
        [addExpVc setSelectCallback:^(NSString *yearStr, NSString *detailStr,NSString *ID) {
            weakItem.title = yearStr;
            weakItem.subTitle = detailStr;
            weakItem.ID = ID;
            [self reloadTableView];
        }];
        
        [self.navigationController pushViewController:addExpVc animated:YES];
    }else {
        UserExperienceCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.isSelectCell = !cell.isSelectCell;
        
        if (cell.isSelectCell) {
            [self.seleteExpArray addObject:item];
        }else {
            [self.seleteExpArray removeObject:item];
        }
        
        if (self.seleteExpArray.count > 0) {
            self.bottomDeleteBtn.enabled = YES;
        }else {
            self.bottomDeleteBtn.enabled = NO;
        }
        
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserGroup *group = self.groups[indexPath.section];
    UserItem *item = group.items[indexPath.row];
    
    return [self tabelViewRowHeightWith:item isEdit:self.isDeleting];
}



// 计算行高
- (CGFloat)tabelViewRowHeightWith:(UserItem *)item isEdit:(BOOL)isEdit {
    //Unit.years
    NSString *yearStr = _isChinese ? [NSString stringWithFormat:@"%@年", item.title] : item.title;
    
    CGSize yearStrSize = [yearStr textSizeWithtextMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:[UIFont systemFontOfSize:16]];
    CGSize subStrSize = CGSizeZero;
    if (isEdit) {
        subStrSize = [item.subTitle textSizeWithtextMaxSize:CGSizeMake((kYFScreenWidth - yearStrSize.width - kExperienceCellMargin * 3 - 25), MAXFLOAT) font:[UIFont systemFontOfSize:15]];
    }else {
        subStrSize = [item.subTitle textSizeWithtextMaxSize:CGSizeMake((kYFScreenWidth - yearStrSize.width - kExperienceCellMargin * 2), MAXFLOAT) font:[UIFont systemFontOfSize:15]];
    }
    
    return (subStrSize.height + 28);
}
#pragma mark - 设置添加成就视图
- (void)creatAddExperienceView {
    
    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
    [addButton setImage:[UIImage imageNamed:@"添加"] forState:UIControlStateNormal];
    
    CGSize size = [@"2013年" textSizeWithtextMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:[UIFont systemFontOfSize:16]];
    
    addButton.frame = CGRectMake(0, 0, (size.width + kExperienceCellMargin * 2), kAutoHei(64));
    addButton.adjustsImageWhenHighlighted = NO;
    
    
    UILabel *titleLabel = [[UILabel alloc] init];
    
    titleLabel.text = NSLocalizedString(@"Add Achievement", @"添加成就");
    titleLabel.font = SanFranciscoFont(18);
    titleLabel.textColor = [UIColor blackColor];
    
    [titleLabel sizeToFit];
    titleLabel.x = size.width + kExperienceCellMargin * 2;
    titleLabel.y = 12;
    
    UILabel *subLabel = [[UILabel alloc] init];
    
    subLabel.textColor = kUnSelectedColor;
    
    subLabel.font = [UIFont systemFontOfSize:15];
    subLabel.text = _isChinese ? @"录入您曾参加过的比赛及所获成绩" :  NSLocalizedString(@"Enter the competition and awards you have attended", nil);
    subLabel.numberOfLines = 0;
    subLabel.x = titleLabel.x;
    subLabel.y = CGRectGetMaxY(titleLabel.frame) + 4;
    subLabel.width = kYFScreenWidth - subLabel.x - 16;
    
    CGSize subTextSize = [subLabel.text textSizeWithtextMaxSize:CGSizeMake((kYFScreenWidth - subLabel.x - 16), MAXFLOAT) font:subLabel.font];
    subLabel.height = subTextSize.height;
    
    CGFloat addExpViewHeight = CGRectGetMaxY(subLabel.frame) + 8;
    
    UIView *addExpView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, addExpViewHeight)];
    addExpView.backgroundColor = [UIColor whiteColor];
    
    addButton.height = addExpViewHeight;
    
    [addExpView addSubview:addButton];
    [addExpView addSubview:titleLabel];
    [addExpView addSubview:subLabel];
   

    UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    coverBtn.frame = addExpView.bounds;
    [addExpView addSubview:coverBtn];
    
    [coverBtn addTarget:self action:@selector(addExpClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 创建分割线
    UIView *bottomlineView = [[UIView alloc] initWithFrame:CGRectMake(0, addExpView.height - 0.5, kYFScreenWidth, 0.5)];
    bottomlineView.backgroundColor = kLineBackgroundColor;
    [addExpView addSubview:bottomlineView];
    self.tableView.tableFooterView = addExpView;
}

- (void)addExpClick {
    
    if (self.isDeleting) {
        return;
    }
    
    UserAddExpController *addExpVc = [[UserAddExpController alloc] init];
    
    __weak typeof(self) weakSelf = self;
    
    [addExpVc setSelectCallback:^(NSString *yearStr, NSString *detailStr, NSString *ID) {
        UserItem *item = [UserItem itemWithTitle:yearStr andSubTitle:detailStr];
        item.ID = ID;
        UserGroup *group = weakSelf.groups.firstObject;
        [group.items addObject:item];
        [self reloadTableView];
    }];
    
    [self.navigationController pushViewController:addExpVc animated:YES];
}

#pragma mark - 初始化垃圾篓
- (void)CreatTrashBasketShow:(BOOL)show {
    
    if (show) {
        MTButton *button = [MTButton buttonWithType:UIButtonTypeCustom];
        
        button.frame = CGRectMake(0, kYFScreenHeight, kYFScreenWidth, kAutoHei(64));
        button.backgroundColor = [UIColor whiteColor];
        
        [button setImage:[UIImage imageNamed:@"trackPattern_icon_delete"] forState:UIControlStateDisabled];
        [button setImage:[UIImage imageNamed:@"trackPattern_icon_delete2"] forState:UIControlStateNormal];
        
        [button setTitle:NSLocalizedString(@"Delete", @"删除") forState:UIControlStateDisabled];
        [button setTitle:NSLocalizedString(@"Delete", @"删除") forState:UIControlStateNormal];
        
        [button setTitleColor:kUnSelectedColor forState:UIControlStateNormal];
        [button setTitleColor:kUnSelectedColor forState:UIControlStateDisabled];
        button.enabled = NO;
        button.titleLabel.font = [UIFont systemFontOfSize:11];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        self.bottomDeleteBtn = button;
        [window addSubview:button];
        
        [UIView animateWithDuration:0.25 animations:^{
            button.y = kYFScreenHeight - kAutoHei(64);
        }];
        
        [button addTarget:self action:@selector(bottomDeleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
    }else {
        [UIView animateWithDuration:0.25 animations:^{
            self.bottomDeleteBtn.y = kYFScreenHeight;
        } completion:^(BOOL finished) {
            [self.bottomDeleteBtn removeFromSuperview];
            self.bottomDeleteBtn = nil;
        }];

    }
}

- (void)bottomDeleteBtnClick:(UIButton *)button {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    if (self.seleteExpArray.count > 0) {
        
        NSMutableString *stringM = [NSMutableString string];
 
        
        for (NSInteger i = 0; i < self.seleteExpArray.count; i++) {
            
            UserItem *item = self.seleteExpArray[i];
            if (i == 0) {
                [stringM appendString:item.ID];
            }else {
                [stringM appendFormat:@",%@",item.ID];
            }
        }
        
        YFUserApi *deleteCareerApi = [YFUserApi deleteCareerWithCareerID:stringM complete:^(NSError *error) {
            if (error == nil) {
                [MBProgressHUD hideHUDForView:self.view animated:YES];
                [self loadData];
                [self deleteHandel:self.navigationItem.rightBarButtonItem];
            }else{
                [MBProgressHUD showFailHudInView:self.view message:NSLocalizedString(@"RealTime.Delete failure", nil) afterDelay:1.0];
            }
        }];
    }

}



- (NSMutableArray *)seleteExpArray {
    if (_seleteExpArray == nil) {
        _seleteExpArray = [NSMutableArray array];
    }
    return _seleteExpArray;
}

@end
